package longshu.srpc.api;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * RpcProtocol 负责协议编码/解码
 *
 * @author LongShu 2017/12/03
 */
public interface RpcProtocol {

    byte[] encode(Object object) throws IOException;

    <T> T decode(byte[] bytes, Class<T> genericClass) throws IOException;

    <T> T decode(InputStream in, Class<T> genericClass) throws IOException;

    String getProtocol();

    class ProtocolRegistry {
        /**
         * 存放协议实现方式,如 srpc://host:port 存放 SimpleRpcProtocol
         */
        private static Map<String, RpcProtocol> rpcProtocol = new HashMap<>();

        /**
         * @param protocol     例: srpc://
         * @param protocolImpl 例: SimpleRpcProtocol
         */
        public static void register(String protocol, RpcProtocol protocolImpl) {
            rpcProtocol.put(protocol, protocolImpl);
        }

        public static RpcProtocol getRpcProtocol(String protocol) {
            RpcProtocol rpcProtocol = ProtocolRegistry.rpcProtocol.get(protocol);
            if (rpcProtocol == null) {
                throw new IllegalArgumentException("protocol:[" + protocol + "]not exist !");
            }
            return rpcProtocol;
        }

    }
}
